package com.bt.lms.ui.action.enp;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.EnpBizTypeConstant;
import com.bt.lms.entity.EnrollmentPlan;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.action.enp.vo.SearchEnpVo;
import com.bt.lms.ui.page.enp.EnrollmentPlanList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import org.apache.commons.beanutils.BeanUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.time.LocalDate;

/**
 * 招生计划条件搜索按钮
 *
 * @author 李鹏
 */
public class SearchBtnAction implements EventHandler {

    /**
     * 招生计划主界面
     */
    private EnrollmentPlanList enrollmentPlanList;

    public SearchBtnAction(EnrollmentPlanList enrollmentPlanList) {
        this.enrollmentPlanList = enrollmentPlanList;
    }

    @Override
    public void handle(Event event) {

        //1.获取用户输入，返回VO：里面承载着用户的输入
        SearchEnpVo searchEnpVo = getInParams();//获取参数
        //2.验证用户输入
        String validateMsg = validateInParam(searchEnpVo);
        //3.组包（根据自定义的网络消息协议），inP:VO outP:消息
        byte[] bytes = null;
        if (null == validateMsg) {

            //验证通过，组包
            bytes = handle2ReqMsg(searchEnpVo);

        } else {
            //提示，程序终止
            return;
        }

        //4.组网（根据咱们自定义的网络连接交互规范来定义）inP:服务器的信息（ip,port....）
        Socket socket = getNet();
        //5.发送消息，inP:消息 ouP:是否发送成熟
        boolean flag = send(socket, bytes);

    }

    /**
     * 发送消息
     * 1.将消息转为字节流
     * 2.发送
     *
     * @param socket 发生的socket
     * @param bytes  要发送的消息
     * @return
     */
    private boolean send(Socket socket, byte[] bytes) {

        //发送消息
        try {
            OutputStream out = socket.getOutputStream();
            out.write(bytes); //写
            out.flush();//冲刷，立刻发出去

            //接收回应消息
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            in.read(buf); //读
            RespMsg respMsg = RespMsg.toRespMsg(buf);
            String data = respMsg.getData();

        } catch (IOException e) {
//            throw new RuntimeException(e);
        }
        return true;
    }


    /**
     * 获取网络
     *
     * @return socket
     */
    private Socket getNet() {
        //ip和端口号
        String serverIp = "127.0.0.1";
        int serverPort = 8888;
        Socket socket = null;
        try {
            socket = new Socket(serverIp, serverPort);
        } catch (IOException e) {
//            throw new RuntimeException(e);
            return null;
        }

        return socket;
    }


    /**
     * 将用户输入的信息处理成我们规定的请求信息
     *
     * @param searchEnpVo 用户输入的消息
     * @return 请求消息
     */
    private byte[] handle2ReqMsg(SearchEnpVo searchEnpVo) {
        //消息
        ReqMsg reqMsg = new ReqMsg();
        //课程信息实体类
        EnrollmentPlan enrollmentPlan = new EnrollmentPlan();
        //业务类型
        reqMsg.setBizType(EnpBizTypeConstant.ENP_PLAN_PAGE_CONDITION_QUERY);
        //vo转实体类
        try {
            //属性复制
            BeanUtils.copyProperties(enrollmentPlan, searchEnpVo);
            enrollmentPlan.setId(1L);
            enrollmentPlan.setTeachPlanId(2L);
            //转JSON
            String enpStr = JSON.toJSONString(enrollmentPlan);
            //数据带走
            reqMsg.setData(enpStr);

        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        //转总数组
        byte[] bytes = reqMsg.toBytes();

        return bytes;
    }


    /**
     * 2.验证
     *
     * @param searchEnpVo 用户输入的数据
     * @return 验证的结果
     */
    private String validateInParam(SearchEnpVo searchEnpVo) {

        String msg = ""; //所有提示信息

        String enpName = searchEnpVo.getPlanName();//招生计划名称
        String nameBlankMsg = "招生计划名称必须填写！\r\n";
        String nameLengthMsg = "招生计划名称长度在18位以下，包含18！\r\n";
        if ("".equals(enpName)) {
            msg += nameBlankMsg;
        } else {
            if (enpName.length() > 18) {
                msg += nameLengthMsg;
            }
        }

        //报名开始时间
        LocalDate startDate = searchEnpVo.getStartTime();
        if (startDate == null) {
            msg += "请选择报名开始时间!\r\n";
        }

        //报名结束时间
        LocalDate stopDate = searchEnpVo.getStopTime();
        if (stopDate == null) {
            msg += "请选择报名结束时间!\r\n";
        }
        if (!(stopDate == null)) {
            int startTimeYear = startDate.getYear();//开始时间
            int stopTimeYear = stopDate.getYear();//结束时间


            if (stopTimeYear >= startTimeYear) {//不能在报名开始时间之前
                int startTimeMonth = startDate.getMonthValue();
                int stopTimeMonth = stopDate.getMonthValue();
                if (stopTimeMonth >= startTimeMonth) {
                    int startDay = startDate.getDayOfMonth();
                    int stopDay = stopDate.getDayOfMonth();

                } else {
                    msg += "请选择正确的报名结束时间，结束时间不能小于开始时间（月）\r\n";
                }

            } else {
                msg += "请选择正确的报名结束时间，结束时间不能小于开始时间（年）\r\n";
            }
        }

        //处理返回
        if ("".equals(msg)) {
            msg = null;
        }
        if (!(msg == null)) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(msg);
            alert.show();

            return null;
        }

        return msg;
    }

    /**
     * 获取用户输入
     *
     * @return 招生计划分页条件
     */
    private SearchEnpVo getInParams() {

        //VO对象
        SearchEnpVo searchEnpVo = new SearchEnpVo();

        //招生计划名称
        TextField nameTf = (TextField) enrollmentPlanList.lookup("#nameTf");
        String nameStr = nameTf.getText().trim();
        searchEnpVo.setPlanName(nameStr);

        //计划状态
        ComboBox statusCom = (ComboBox) enrollmentPlanList.lookup("#statusCom");
        //获取计划状态输入
        String value = (String) statusCom.getValue();
        Integer level = -1;
        switch (value) {
            case "未开始":
                level = 1;
                break;
            case "报名中":
                level = 2;
                break;
            case "审核中":
                level = 3;
                break;
            case "已完成":
                level = 4;
                break;
            case "全部":
                level = 5;
                break;
        }
        searchEnpVo.setStatus(level);

        //按开始时间查询
        ComboBox timeCom = (ComboBox) enrollmentPlanList.lookup("#timeCom");
        //获取用户输入
        String value1 = (String) timeCom.getValue();
        Integer level1 = -1;
        switch (value1) {
            case "未开始":
                level1 = 1;
                break;
            case "报名中":
                level1 = 2;
                break;
            case "审核中":
                level1 = 3;
                break;
            case "已完成":
                level1 = 4;
                break;
            case "全部":
                level1 = 5;
                break;
        }
        searchEnpVo.setTimeSearch(level1);

        //开始时间
        DatePicker startTimeDp = (DatePicker) enrollmentPlanList.lookup("#startTimeDp");
        LocalDate startDate = startTimeDp.getValue();
        searchEnpVo.setStartTime(startDate);

        //结束时间
        DatePicker stopTimeDp = (DatePicker) enrollmentPlanList.lookup("#stopTimeDp");
        LocalDate stopDate = stopTimeDp.getValue();
        searchEnpVo.setStopTime(stopDate);

        return searchEnpVo;
    }
}
